package com.zipou.framework.gwt.client.widget;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.google.gwt.user.client.rpc.IsSerializable;
import com.google.gwt.user.client.ui.ListBox;

public class MyListBox <T extends IsSerializable> extends ListBox {

	private List<T> array;


	public MyListBox() {
		array = new ArrayList<T>();
		this.setEnabled(false);
	}

	final public void addElement(T object ) {
		array.add(object);
		this.addItem(object.toString());
	}
	
	@Deprecated
	final public void populate(Set<T> o) {	
		/**
		 * FIXME ! C'est moche
		 */
		//this.array = (List<T>) Arrays.asList(o.toArray());
		ArrayList<T> a = new ArrayList<T>();
		for (T aa : o ) {
			a.add(aa);
		}
		array = a;
		
		if (o.size() == 0) {
			this.setEnabled(false);
		} else {
			for (T one : array) {
				this.addItem(one.toString());
			}
			this.setEnabled(true);
		}
	}	
	
	final public void populate(List<T> o) {	
		if (o.size() == 0) {
			this.setEnabled(false);
		} else {
			for (T one : o) {
				this.addItem(one.toString());
			}
			this.setEnabled(true);
		}
	}

	final public void setSelectedElement(T el) {
		int i = 0;
		for (T t : array) {
			if(t.toString().equals(el.toString())) {
				this.setSelectedIndex(i);
			}
			i++;
		}
	}

	final public T getSelectedElement() {
		if (array.size() != 0) {
			return this.array.get(this.getSelectedIndex());
		}
		return null;
	}

	final public T getElementById(String id) {
		for (T t : array) {
			if(t.toString().equals(id)) {
				return t;
			}
		}
		return null;
	}

	final public List<T> getAll() {
		return array;
	}

}